package day4.demo1_读写锁;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {
    ReadWriteLock loc = new ReentrantReadWriteLock();
    public static void main(String[] args) throws Exception{
        Test t = new Test();
        new Thread("A"){
            @Override
            public void run() {
                try {
                    t.read_lock();
                } catch (Exception e) {}
            }
        }.start();

        Thread.sleep(500);

        new Thread("B"){
            @Override
            public void run() {
                try {
                    t.write_lock();
                } catch (Exception e) {}
            }
        }.start();
    }
    synchronized void read_sync()throws Exception{
        System.out.println(Thread.currentThread().getName()+"执行方法：read_sync");
        System.out.println("执行读操作。。。。");
        Thread.sleep(5000);
    }
    synchronized void write_sync()throws Exception{
        System.out.println(Thread.currentThread().getName()+"执行方法：write_sync");
        System.out.println("执行写操作。。。。");
        Thread.sleep(5000);
    }

    void read_lock()throws Exception{
        loc.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"执行方法：read_lock");
        System.out.println("执行读操作。。。。");
        Thread.sleep(5000);
        loc.readLock().unlock();
    }
    void write_lock()throws Exception{
        loc.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"执行方法：write_lock");
        System.out.println("执行写操作。。。。");
        Thread.sleep(5000);
        loc.writeLock().unlock();
    }
}
